<!--  -->
<template>
    <div style="width: 100%;">
        <div style="margin:20px 0px;">
            <div>
                <el-input
                    v-model="comment.content"
                    autosize
                    type="textarea"
                    placeholder="请输入评论内容"
                    maxlength="200"
                    show-word-limit
                />
                <el-button style="float: right;margin: 10px 0px;" type="primary" @click="addComment">发表评论</el-button>
            </div>

            <div style="margin: 10px 0px; font-size: 24px;padding: 10px 0px;border-bottom: 1px solid rgb(82, 82, 82);text-align: left;">评论列表</div>

            <div class="comment" style="80%">
                <div v-for="(item, index) in comments" :key="index" style="flex-direction: column;">
                    <div style="display: flex; padding: 5px;cursor: pointer;">
                        <el-avatar
                            style="width: 50px;height: 50px;"
                            :size="32"
                            class="mr-3"
                            :src="item.user_gravatar!=''?item.user_gravatar:'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
                            @click="toMine(item.u_id)"
                        />
                        <div style="margin: 5px;">
                            <div style="display: flex;">
                                <el-text line-clamp="2">
                                {{item.username!=''?item.username:'张三'}}
                                </el-text>
                                <div style="display: flex;align-items: end;margin-left: 10px;">
                                    <el-text>
                                        {{item.createtime!=''?dateStr(item.createtime):'2023-03-29 15:30:00'}}
                                    </el-text>
                                </div>
                            </div>
                            <div style="padding: 3px 0px;text-align: left;"><el-text>{{ item.content }}</el-text></div>
                            <div style="display: flex;">
                                <el-button type="text" @click="replyForRoot(item)">回复</el-button>
                                <el-button v-if="isdelete" icon="DeleteFilled" type="text" @click="delComment(item)">删除</el-button>
                            </div>
                        </div>
                    </div>
                    <div v-if="JSON.stringify(item.children) != '[{}]' " v-for="it in item.children" :key="it.c_id" style="display: flex; padding: 5px;margin-left: 50px;width: 100%;">
                        <el-avatar
                            style="width: 50px;height: 50px;cursor: pointer;"
                            :size="32"
                            class="mr-3"
                            :src="it.user_gravatar!=''?it.user_gravatar:'https://avatars.githubusercontent.com/u/27342882?v=4&size=64'"
                            @click="toMine(it.u_id)"
                        />
                        <div style="margin: 5px;">
                            <div style="display: flex;">
                                <el-text line-clamp="2">
                                    {{it.username!=''?it.username:'李四'}}
                                </el-text>
                                <div style="display: flex;align-items: end;margin-left: 10px;">
                                    <el-text>
                                        {{it.createtime!=''?dateStr(it.createtime):'2023-03-29 15:30:00'}}
                                    </el-text>
                                </div>
                            </div>
                            <div style="padding: 3px 0px;text-align: left;"><el-text type="primary">{{ it.username }}</el-text> 回复<el-text type="primary"> @{{it.target}}：</el-text><el-text>{{ it.content }}</el-text></div>
                            <div style="display: flex;">
                                <el-button type="text" @click="replyForRoot(it,item.c_id)">回复</el-button>
                                <el-button v-if="isdelete" icon="DeleteFilled" type="text" @click="delComment(it)">删除</el-button>
                                
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="JSON.stringify(comments) == '[]'" style="height: 200px;">
                    <el-text>
                        没有更多评论了
                    </el-text>
                </div>
            </div>
        </div>
    </div>

    <!-- 回复评论组件 -->
    <el-dialog v-model="dialogFormVisible" :title="`回复 ${this.childComment.target}`">
    <el-form :model="this.childComment">
      <el-form-item label="输入一个友好的评论" :label-width="formLabelWidth">
        <el-input v-model="this.childComment.content" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false,sendChildComment()">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
    name: 'comment',
    components: {},
    props: {
        author_id:Number,
        default:0
    },
    data() {
        return {
            comment: {      //对应后端的comment对象
                // c_id: '数据标识id',
                content: '评论信息',   
                username: '用户名称',
                user_gravatar: '用户头像',
                u_id: '用户id',
                r_id: '文章id *',
                p_id: '父评论id 空表示该评论为根节点，非空表示为子节点',
                target: '回复对象的名字',
                // createtime: '创建时间',
                // children:[] //子回复
            },
            comments:[{1:2,3:4}],    //评论队列
            showButton:false,
            formLabelWidth : '140px',

            dialogFormVisible:false,   //子回复框是否显示
            childComment:{             //点击 回复 后的子评论
                content:'',
                username:'',
                user_gravatar:'',
                u_id:'',
                r_id:'',
                p_id:'',
                target:''
            },

            isdelete:false,    //是否拥有删除权限
        }
    },
    computed: {},
    watch: {},
    methods: {
        //触发跳转到个人主页功能
        toMine(id){        //跳转到个人主页
            console.log(id);
            this.$emit('toMine',id)
        },
        delComment(i){       //删除评论
            console.log("c_id:"+i.c_id+"--r_id:"+this.$route.query.id+"--p_id:"+i.p_id+"--");
            axios.get('http://localhost:8888/comment/delComment',{
                params:{
                    c_id:i.c_id,
                    r_id:this.$route.query.id,
                    p_id:i.p_id
                }
            }).then(data=>{  
                ElMessage({
                    // showClose: true,
                    message: '删除成功.',
                    type: 'success',
                })
                this.$router.go(0)
            })
        },
        // -------------
        real_time_loading(Comment){    //实时加载方法，直接将数据展示出来
            //实时加载刚发送的数据
            let flag = false    //奇怪的bug，不管有没有flag限制它的情况，两种push都会执行.现已解决
            if(Comment.c_id == undefined){       //没有c_id，说明是根节点，因为c_id是后端赋值
                flag = true
            }
            //还是有bug，逻辑有问题
                //由于时间属性是后端设置的，所以这里要自己赋值
                Comment.createtime=new Date()
                this.comments.forEach(element => {
                    if(element.c_id===Comment.p_id){
                        element.children.unshift(Comment)  //unshift从开头插入,push从末尾插入
                        flag = false
                        return
                    }
                })

            if(flag) this.comments.unshift(Comment)
            this.comment={}
        },
        sendChildComment(){    //回复评论 确定发送
            if(this.childComment.content.trim()==='' || this.childComment.content.length<1) return this.$message.error('评论不能为空')
            axios.post('http://localhost:8888/comment/save',this.childComment).then(data=>{
                ElMessage({
                    // showClose: true,
                    message: '回复评论成功.',
                    type: 'success',
                })
            }).catch(err=>{
                ElMessage({
                    // showClose: true,
                    message: '当前繁忙，请稍后再试.',
                    type: 'error',
                })
            })
            this.replyForRootContent=''
            this.real_time_loading(this.childComment)
            this.childComment={}
            // this.$router.go(0)
        },
        replyForRoot(i,item_cid){    //点击回复 回复评论
            console.log(i);
            console.log(item_cid);
            // if(i.username == this.$store.state.user.username){
            //     return this.$message.error('不能回复自己的评论')
            // }
//修改的原因是我懒得在后端写子评论下的多级子评论代码，干脆同属一个根评论下，便于管理和前端显示
//对子评论回复时，获得根回复的id，及属于该根路径下，便于前端显示
            if(item_cid){           //子评论下评论，根路径不取子评论，取同属根路径作为父节点
                this.childComment.p_id = item_cid;
            }else{                  //根路径评论，取根路径作为父节点
                this.childComment.p_id = i.c_id;
            }
            this.childComment.target = i.username;
            this.childComment.r_id = this.$route.query.id;
            this.childComment.u_id = this.$store.state.user.u_id;
            this.childComment.username = this.$store.state.user.username;
            this.childComment.user_gravatar = this.$store.state.user.picture;
            this.dialogFormVisible=true;
            // this.real_time_loading(this.childComment)
        },
        getComments(){      //加载评论
            axios.get('http://localhost:8888/comment/articleComment',{
                params:{
                    a_id: this.$route.query.id
                }
            }).then(data=>{
                console.log(data.data);
                this.comments = data.data.data
            })
        },
        addComment(){       //添加根节点节点评论
            let saveComment={}
            saveComment.content = this.comment.content
            saveComment.username = this.$store.state.user.username
            saveComment.user_gravatar = this.$store.state.user.picture
            saveComment.u_id = this.$store.state.user.u_id
            saveComment.r_id = this.$route.query.id
            // saveComment.p_id = ''
            // saveComment.target = ''
            if(saveComment.content.trim()==='' || saveComment.content.length<1) return this.$message.error('评论不能为空')
            axios.post('http://localhost:8888/comment/save',saveComment).then(data=>{
                ElMessage({
                    // showClose: true,
                    message: '评论成功.',
                    type: 'success',
                })
            }).catch(err=>{
                ElMessage({
                    // showClose: true,
                    message: '当前繁忙，请稍后再试.',
                    type: 'error',
                })
            })
            this.real_time_loading(saveComment)
            // this.$router.go(0)
        },
        dateStr(date) {
            const now = new Date();
            const diff = now.getTime() - new Date(date).getTime();
            const seconds = Math.floor(diff / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);
            const months = Math.floor(days / 30);
            const years = Math.floor(months / 12);
            // console.log(now.getTime()-date);
            if (seconds < 60) {
                return "刚刚";
            } else if (seconds < 60 * 60) {
                return `${minutes} 分钟前`;
            } else if (seconds < 60 * 60 * 24) {
                return `${hours} 小时前`;
            } 
            // else if (seconds < 60 * 60 * 24 * 7) {
            //     return `${days} 天前`;
            // } else if (seconds < 60 * 60 * 24 * 30) {
            //     return `${months} 个月前`;
            // } else if (seconds < 60 * 60 * 24 * 365) {
            //     return `${years} 年前`;
            // } 
            else {
                const dateTime = new Date(date);
                const year = dateTime.getFullYear();
                const month = dateTime.getMonth() + 1;
                const day = dateTime.getDate();
                return `${year}/${month}/${day}`;
            }
        }


    },
    created() { 
        if(JSON.stringify(this.$store.state.user)  == '{}')this.$router.push('/login')
        this.getComments()
        console.log(JSON.stringify(this.comments));
        this.comment={}
        this.isdelete=(this.author_id === this.$store.state.user.u_id) || (this.$store.state.user.isAdmin == '0')
        console.log('isdelete:'+this.isdelete);
    },  
    mounted() { }
}
</script>

<style scoped></style>
